import Vue from 'vue';
import axios from 'axios';

class TCommKms {
    constructor() {
        this.config = {
            clientId: ['c', (new Date()).getTime(), parseInt(100 * Math.random())].join(''),
            apiUrl: "https://localhost:31021",
            //apiUrl: "https://dq.hhdata.cn:31022",
            dbKey: "cock",
            kms: {
                tagKey: "commKmsV10",
                kmsUrl: "wss://meeting.xmgkfw.com:31003/kurento",
                ice: {
                    stun: "stun:211.95.25.189:3478",
                    turn: {
                        url: "turn:211.95.25.189:3478",
                        uid: "kurento",
                        pwd: "kurento"
                    }
                }
            }
        };
        this.kmsClient = null;
        this.cameras = [];
    };
    getClient() {
        var me = this;
        return new Promise((success, faild) => {
            try {
                if (me.kmsClient && me.kmsClient != null) {
                    success(me.kmsClient);
                } else {
                    kurentoClient(me.config.kms.kmsUrl, function(erClient, client) {
                        client.on('disconnect', () => {
                            delete me.kmsClient;
                        });
                        me.kmsClient = client;
                        client.getServerManager().then(_svr => {
                            client.svr = _svr;
                            return client.svr.getSessions();
                        }).then(_sessions => {
                            client.svr.sessions = _sessions;
                            return client.svr.getKmd();
                        }).then(_kmd => {
                            client.svr.kmd = _kmd;
                            success(me.kmsClient);
                        })
                    });
                }
            } catch (error) {
                console.log(error);
                success(me.kmsClient);
            }
        });
    };
    registObj(obj, objCode, objInfo) {
        var me = this;
        return Promise((success, faild) => {
            try {
                var info = objInfo || {};
                var arr = obj.id.split(".");
                info.kmsId = obj.id;
                info.kmsType = arr[arr.length - 1];
                info.code = objCode;
                me.getClient().then(client => {
                    var key = [me.config.kms.tagKey, obj.id].join("_");
                    var content = JSON.stringify(info);
                    return client.svr.addTag(key, content);
                }).then(_ => {
                    obj.objInfo = info;
                    success(obj);
                })
            } catch (error) {
                console.log(error);
                success(me.kmsClient);
            }
        });
    };
    getTags() {
        var me = this;
        var tags = {
            items: [],
            dict: {}
        };
        return Promise((success, faild) => {
            try {
                me.getClient().then(client => {
                    return client.svr.getTags();
                }).then(_tags => {
                    _tags.forEach(t => {
                        var k = t.key;
                        if (k.indexOf(me.config.kms.tagKey) == 0) {
                            var info = JSON.parse(t.value);
                            tags.dict[info.kmsId] = info;
                            tags.items.push(info);
                        }
                    });
                    success(tags);
                })
            } catch (error) {
                console.log(error);
                success(tags);
            }
        });
    };
    getChannels() {
        var me = this;
        var res = {
            items: [],
            dict: {},
            tags: null
        };
        return Promise((success, faild) => {
            try {
                me.getTags().then(_tags => {
                    res.tags = _tags;
                    return me.kmsClient.svr.getPipelines();
                }).then(_pipes => {
                    _pipes.forEach(pipe => {
                        var tag = res.tags[pipe.id];
                        if (tag && tag != null && tag.kmsType == "MediaPipeline") {
                            pipe.objInfo = tag;
                            res.items.push(pipe);
                            res.dict[pipe.id] = pipe;
                        }
                    });
                    success(res);
                });
            } catch (error) {
                console.log(error);
                success(res);
            }
        });
    };
    getChannel(channelCode) {
        var me = this;
        var res = {
            channel: null,
            tags: null
        };
        return Promise((success, faild) => {
            try {
                me.getChannels().then(chs => {
                    res.tags = chs.tags;
                    res.channel = chs.items.find(c => {
                        return c.objInfo && c.objInfo.code == channelCode;
                    });
                    success(res);
                })

            } catch (error) {
                console.log(error);
                success(res);
            }
        });
    };
    getChannelSeats(channelCode) {
        var me = this;
        var res = {
            channel: null,
            seats: {
                items: [],
                dict: {}
            },
            tags: []
        };
        return Promise((success, faild) => {
            try {
                me.getChannel().then(ch => {
                    res.tags = ch.tags;
                    res.channel = ch.channel;
                    if (res.channel && res.channel != null) {
                        res.channel.getChildren().then(_items => {
                            var pts = _items.filter(item => {
                                var arr = item.id.split(".");
                                var flag = arr[arr.length - 1] == "PassThrough";
                                return flag;
                            });
                            pts.forEach(pt => {
                                var key = [me.config.kms.tagKey, pt.id].join("_");
                                pt.objInfo = res.tags[key];
                                res.seats.items.push(pt);
                                res.seats.dict[pt.id] = pt;
                            });
                            success(res);
                        })
                    } else {
                        success(res);
                    }
                });
            } catch (error) {
                console.log(error);
                success(res);
            }
        });
    };
    loadChannel(channelCode) {
        var me = this;
        var res = {
            channel: null,
            tags: null
        };
        return Promise((success, faild) => {
            try {
                me.getChannel(channelCode).then(_ch => {
                    res = _ch;
                    if (res.channel && res.channel != null) {
                        success(res);
                    } else {
                        me.kmsClient.create("MediaPipeline").then(p => {
                            var info = {
                                modelType: "channel",
                                channelCode: channelCode
                            };
                            res.channel = p;
                            return me.registObj(p, info);
                        }).then(_ => {
                            res.tags.items.push(res.channel.objInfo);
                            res.tags[res.channel.id] = res.channel.objInfo;
                            success(res);
                        })
                    }
                })

            } catch (error) {
                console.log(error);
                success(res);
            }
        });
    };


};
Vue.prototype.commKms = new TCommKms();